/**
 * Created by leiqr on 2015/6/8.
 * 运营中心首页
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var template = require("template");
    require('jquerycookie');
    require('./topNotice');
    require('jqueryAppear');
    require('jquerySuperslide');
    require('./toTop');
    //require('jqueryBizQQ');
    var tip = require('js/tip');
    var dialogModule = require('js/goToLogin');

    var api_prefix = api_domain + "/"; //api前缀
    var jsopName = "jsonp_data";

    var main = {
        init: function () {
            var self = this,
                defer = this.requestData();
            defer.then(function (res) {
                if (!res) {
                    dialogModule.dialog.showModal();
                    return;
                }
                self.bindEvt();
                self.fillData(res)
                self.animationOnScroll();
                self.fullSlide();
                self.generateQrcode();
                self.getSimilarArticles(res.tag)
                    .then(function (res) {
                        if (!res) {
                            dialogModule.dialog.showModal();
                            return;
                        }
                        self.fillSimilars(res);
                    })
            })
            //$.BizQQ([{selector: 'js_BizQQWPA'},{selector: 'BizQQWPABC'},{selector: 'BizQQWPABCD'}]);
            
            this.getPraiseData()
                .then(function(res){
                    if (!res) {
                        dialogModule.dialog.showModal();
                        return;
                    }
                    if (res.success) {
                        $('#praiseArea').show().find('#praiseCount').html(res.num);
                    }                  
                })
        },
        generateQrcode: function () {
            var me = this;
            var url = api_prefix + 'api/index.php?r=/cms/cms-data/imageurl&url=' + encodeURIComponent(location.href);
            $("#qrImg").attr('src',url);
        },
        getQueryParams: function (para) {
            var reg = new RegExp("(^|&)" + para + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return decodeURIComponent(r[2]);
            }
            return null;
        },
        bindEvt: function () {
            var me = this;
            $('#bds_erweimai').click(function (e) {
                $("#qrcode_con").show();
                e.stopPropagation();
            }).hover(function () {
                $("#qrcode_con").show();
            }, function () {
                $("#qrcode_con").hide();
            });
            $('body').click(function () {
                $("#qrcode_con").hide();
            })
            $('#navbar').click(function(e){
                var target = $(e.target);
                
                var aid = target.data('aid') || target.parent().data('aid');
                
                if (aid !== undefined) {
                    var pid = target.data('pid') || target.parent().data('pid');
                    location.href = "list.html?dirId=" + aid + "&pid=" + pid;
                }
            });
            $('#praise').click(function(e){
                me.praiseArticle()
                    .then(function(res){
                        if (!res) {
                            dialogModule.dialog.showModal();
                            return;
                        }
                        if (!res.success) {
                            tip.showError(res.msg);
                            return;
                        }
                        $('#praiseCount').html(res.num);
                        //todo
                    })
            })
        },

        requestData: function () {
            var self = this;
            var id = this.getQueryParams('articalId') || '';
            var url = api_prefix + "api/index.php?r=cms/cms-data/get-article-info&id=" + id + "&jsonp=" + jsopName;
            var defer = $.Deferred();
            $.getScript(url, function () {
                defer.resolve(window[jsopName]);
            });
            return defer.promise();
        }

        ,
        /**
         * 对日期进行格式化，
         * @param date 要格式化的日期
         * @param format 进行格式化的模式字符串
         *     支持的模式字母有：
         *     y:年,
         *     M:年中的月份(1-12),
         *     d:月份中的天(1-31),
         *     h:小时(0-23),
         *     m:分(0-59),
         *     s:秒(0-59),
         *     S:毫秒(0-999),
         *     q:季度(1-4)
         * @return String
         */
        dateFormat: function (date, format) {
            var reg = /\d+/g;
            if (reg.test(date)) {
                date = ( date - 0) * 1000;
            }
            date = new Date(date);
            var map = {
                "M": date.getMonth() + 1, //月份
                "d": date.getDate(), //日
                "h": date.getHours(), //小时
                "m": date.getMinutes(), //分
                "s": date.getSeconds(), //秒
                "q": Math.floor((date.getMonth() + 3) / 3), //季度
                "S": date.getMilliseconds() //毫秒
            };
            format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
                var v = map[t];
                if (v !== undefined) {
                    if (all.length > 1) {
                        v = '0' + v;
                        v = v.substr(v.length - 2);
                    }
                    return v;
                }
                else if (t === 'y') {
                    return (date.getFullYear() + '').substr(4 - all.length);
                }
                return all;
            });
            return format;
        }
        ,

        /**
         * 填充数据
         * @param   res Obj
         */
        fillData: function (res) {
            if (res) {
                var title = res.title || '';
                if (title.length > 12) {
                    title = title.substring((0, 12)) + '...';
                }
                $("#title").html(res.title);
                $("#artical").html(res.content);
                if (res.tag) {
                    $("#articalTag").show().find('#tags').html(res.tag);
                }

                var fileHtmlBuf = [];

                var files = res.files;

                if (files) {
                    //todo xss, html encode
                    for (var i = 0; i < files.length; i++) {
                        var file = files[i];
                        fileHtmlBuf.push('<br><span>' + file.name + '</span><a target="_blank" href="' + file.url + '"><img src="images/icon/download.png" style="margin-left: 10px;cursor: pointer;"></a>');
                    }
                }
                if (fileHtmlBuf.length) {
                    $('#downloadFile').show().append(fileHtmlBuf.join(''));
                }
                           
                $("#auther").html(res.modified_by);
                var category = this.getQueryParams('category'),
                    sub = this.getQueryParams('sub');
                if (sub) {
                    $("#category").html(category + ' > ' + '<span class="c_orange">' + sub + '</span>');
                } else {
                    $("#category").html(category).addClass('c_orange');
                }
                $("#time").html(this.dateFormat(res.modified_time || new Date(), 'yyyy年 MM月 dd日'));             
            }
        }
        ,
        animationOnScroll: function () {
            $('.animated').appear(function () {
                var elem = $(this);
                var animation = elem.data('animation');
                if (!elem.hasClass('visible')) {
                    var animationDelay = elem.data('animation-delay');
                    if (animationDelay) {
                        setTimeout(function () {
                            elem.addClass(animation + " visible");
                        }, animationDelay);
                    } else {
                        elem.addClass(animation + " visible");
                    }
                }
            });
        }
        ,
        fullSlide: function () {
            $(".fullSlide").hover(function () {
                $(this).find(".prev,.next").stop(true, true).fadeIn()
            }, function () {
                $(this).find(".prev,.next").fadeOut()
            });
            $(".fullSlide").slide({
                titCell: ".hd",
                mainCell: ".bd",
                effect: "fold",
                autoPlay: true,
                autoPage: true,
                trigger: "click",
                startFun: function (i) {
                    var curLi = $(".fullSlide .bd li").eq(i);
                    if (!!curLi.attr("_src")) {
                        curLi.css("background-image", curLi.attr("_src")).removeAttr("_src")
                    }
                }
            });
        },
        fillSimilars: function(res){
            var html = template('articles',{articles: res.data})
            $('#similarArticles').show().find("#similarList").html(html);
        },
        getSimilarArticles: function(tag){
            var self = this;
            var id = this.getQueryParams('articalId') || '';
            var url = api_prefix + "api/index.php?r=cms/cms-search/search&keyword=" + tag + "&limit=3&offset=1&jsonp=" + jsopName + "&id=" + id;
            var defer = $.Deferred();
            $.getScript(url, function () {
                defer.resolve(window[jsopName]);
            });
            return defer.promise();
        },
        getPraiseData: function(){
            var self = this;
            var id = this.getQueryParams('articalId') || '';
            var url = api_prefix + "api/index.php?r=cms/cms-search/get-pv&jsonp=" + jsopName + "&id=" + id;
            var defer = $.Deferred();
            $.getScript(url, function () {
                defer.resolve(window[jsopName]);
            });
            return defer.promise();
        },
        praiseArticle: function(){           
            var self = this;
            var id = this.getQueryParams('articalId') || '';
            var url = api_prefix + "api/index.php?r=cms/cms-search/update-pv&jsonp=" + jsopName + "&id=" + id;
            var defer = $.Deferred();
            $.getScript(url, function () {
                defer.resolve(window[jsopName]);
            });
            return defer.promise();
        }
    };
    main.init();
})
;








